<?php
namespace app\api\controller\v1;
class Cart extends Base{

    public function __construct() {
        parent::__construct();
        $this->checkLogin();
    }
    /**
     * 添加购物车
     */
    public function add(){
        $d = $this->post();
        $goods_info = $this->db->find("goods",$d["goods_id"]);
        if(!$goods_info){
            err('商品参数错误!');
        }
        if($d["attr_id"] == 0){
            err('未选择规格!');
        }
        $goods_price = $this->db->find("goods_price",$d["attr_id"]);
        if($goods_price["stock"] < $d['nums']){
            err('库存不足!');
        }
        $rs = $this->db->query('select * from order_cart where user_id = ? and goods_id = ? and goods_price_id = ?',[$this->userinfo['id'],$goods_price['goods_id'],$goods_price['id']],1);
        $cart_count = $d['nums'];
        if($rs){
            $cart_count += $rs['nums'];
            $rs = $this->db->update('order_cart',['nums'=>$cart_count],['user_id = ? and goods_id = ? and goods_price_id = ?',[$this->userinfo['id'],$goods_price['goods_id'],$goods_price['id']]]);
        }else{
            $data = [
                'user_id'=>$this->userinfo['id'],
                'goods_id'=>$goods_price['goods_id'],
                'goods_price_id'=>$goods_price['id'],
                'nums'=>$cart_count,
                'create_time'=>time(),
            ];
            $this->db->insert('order_cart',$data);
        }
        suc(["msg"=>"添加购物车成功","count"=>$cart_count]);
    }

    /**
     * 用户购物车
     */
    public function lists(){
        $cart_list = $this->db->query("
        select
            a.*,b.postage,b.title as goods_name,b.pic,o.nums,c.name as shop_name
        from
            order_cart as o inner join goods_price a on o.goods_price_id = a.id
        left join
            goods b on a.goods_id=b.id
        left join
            shop c on c.id = a.shop_id
        where o.user_id = ?",[$this->userinfo['id']]);
        $cart_total_price = 0;
        if($cart_list){
            //购物数据组装
            foreach ($cart_list as $k => $v){
                $cart_list[$k]["total_price"] = $v['nums']*$v["price"];
            }
            //购物车总价计算
            foreach ($cart_list as $k => $v) {
                $cart_total_price += $v["total_price"];
            }

        }
        $d =[
            'cart_list'=>$cart_list,
            "cart_total_price"=>$cart_total_price,
            "cart_count"=>count($cart_list)
        ];
        suc($d);
    }

    //删除购物车商品
    public function del(){
        $id = $this->post('id');
        $this->db->query('delete from order_cart where user_id = ? and goods_price_id = ?',[$this->userinfo['id'],$id]);
        suc(["msg"=>"删除成功"]);
    }
}
?>
